<?php

namespace App\V3\V3_2_7\Services;

use AlibabaCloud\SDK\Alinlp\V20200629\Alinlp;
use AlibabaCloud\SDK\Alinlp\V20200629\Models\GetNerChEcomRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use App\Services\CommonService;
use App\V3\V3_2_7\Controllers\ExpressController;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\ExpressModel;
use App\V3\V3_2_7\Models\LookMessUserModel;
use App\V3\V3_2_7\Models\MaterielModel;
use App\V3\V3_2_7\Models\MessBoardModel;
use App\V3\V3_2_7\Models\SellModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\SupplierCustomerModel;
use Darabonba\OpenApi\Models\Config;
use Illuminate\Support\Str;

class MessBoardService
{
    public static function addMessBoardContent($data)
    {
        try {
            $i = 0;
            $j = 0;
            $flag = 0;
            $address = '';
            //手机号正则
            $phonePattern = "/^1[3-9]\d{9}$/";
            $content = array_values(array_filter(explode("\n", $data['content'])));
            $contentArr = [];
            foreach ($content as $key => $cVal) {
                if (strpos($cVal, ':') !== false) {
                    $cArr = explode(':', $cVal);
                    if ($cArr[0] == '所在地区' || $cArr[0] == '详细地址') {
                        if (!empty($address)) {
                            $address .= trim($cArr[1]);
                            $contentArr[$i] = $address;
                        } else {
                            $address = trim($cArr[1]);
                        }
                    }
                    if (empty($address)) {
                        $contentArr[$i] = trim($cArr[1]);
                    }
                } else {
                    $contentArr[$i] = trim($cVal);
                }
                $i++;
            }
            if (!empty($address)) {
                $content = array_values($contentArr);
            }
            if (!empty($content[count($content) - 1])) {
                $arr = self::baiDuIdentify($content[count($content) - 1]);
                if (!empty($arr)) {
                    $flag = 1;
                    $data = array_merge($data, $arr);
                    $j = count($content) - 1;
                } else {
                    $kdNo = $content[count($content) - 1];
                    if (strpos($kdNo, ':') !== false
                        || strpos($kdNo, '：') !== false
                        || strpos($kdNo, '--') !== false
                    ) {
                        $kdArr01 = explode(':', $kdNo);
                        $kdArr02 = explode('：', $kdNo);
                        $kdArr03 = explode('--', $kdNo);
                        if (!empty($kdArr01[1])) {
                            $kdNo = $kdArr01[1];
                        }
                        if (!empty($kdArr02[1])) {
                            $kdNo = $kdArr02[1];
                        }
                        if (!empty($kdArr03[1])) {
                            $kdNo = $kdArr03[1];
                        }
                    }
                    $res = ExpressController::autoNumber($kdNo);
                    if (!empty($res)) {
                        $comCode = $res[0]['comCode'];
                        $param = array(
                            'com' => $comCode,  //快递公司编码
                            'num' => $kdNo,           //快递单号
                        );
                        $result = ExpressController::expressData($param);
                        if ($result['message'] == 'ok') {
                            $data['express'] = $content[count($content) - 1];
                        }
                    } else {
                        $name = $content[count($content) - 1];
                        if (strpos($name, ' ') !== false) {
                            $nameArr = array_values(array_filter(explode(' ', $name)));
                            if (!empty($nameArr[1])) {
                                if (preg_match($phonePattern, $nameArr[1])) {
                                    $data['phone'] = $nameArr[1];
                                }
                                $data['name'] = $nameArr[0];
                            }
                        }
                        if (strpos($name, '电话') !== false) {
                            $nameArr = array_values(array_filter(explode('电话', $name)));
                            if (!empty($nameArr[1])) {
                                if (preg_match($phonePattern, $nameArr[1])) {
                                    $data['phone'] = $nameArr[1];
                                }
                                $data['name'] = $nameArr[0];
                            }
                        }

                    }
                }
            }

            if (!empty($content[count($content) - 2]) && empty($flag)) {

                $arr = self::baiDuIdentify($content[count($content) - 2]);
                if (!empty($arr)) {
                    $arr = array_filter($arr);
                    $data = array_merge($data, $arr);
                    $j = count($content) - 2;
                } else {
                    if (empty($data['name']) || empty($data['phone'])) {
                        $name = $content[count($content) - 2];
                        if (strpos($name, ' ') !== false) {
                            $nameArr = array_values(array_filter(explode(' ', $name)));
                            if (!empty($nameArr[1])) {
                                if (preg_match($phonePattern, $nameArr[1])) {
                                    $data['phone'] = $nameArr[1];
                                }
                                $data['name'] = $nameArr[0];
                            }
                        }
                        if (strpos($name, '电话') !== false) {
                            $nameArr = array_values(array_filter(explode('电话', $name)));
                            if (!empty($nameArr[1])) {
                                if (preg_match($phonePattern, $nameArr[1])) {
                                    $data['phone'] = $nameArr[1];
                                }
                                $data['name'] = $nameArr[0];
                            }
                        }
                    }
                }
            }
            if (!empty($content[count($content) - 3]) && empty($flag)) {

                $content[count($content) - 3] = trim($content[count($content) - 3]);
                $arr = self::baiDuIdentify($content[count($content) - 3]);
                if (!empty($arr)) {
                    $arr = array_filter($arr);
                    $data = array_merge($data, $arr);
                    $j = count($content) - 3;
                } else {
                    if (empty($data['name']) || empty($data['phone'])) {
                        if (strpos($content[count($content) - 3], ' ') !== false) {
                            $nameArr = array_values(
                                array_filter(
                                    explode(' ', $content[count($content) - 3])
                                ));
                            if (!empty($nameArr[1])) {
                                if (preg_match($phonePattern, $nameArr[1])) {
                                    $data['phone'] = $nameArr[1];
                                }
                                $data['name'] = $nameArr[0];
                            }
                        }
                    }
                }
            }
            if (!empty($content[count($content) - 2]) && empty($data['phone'])) {
                if (preg_match($phonePattern, $content[count($content) - 2])) {
                    $data['phone'] = $content[count($content) - 2];
                }
            }
            if (!empty($content[count($content) - 3]) && empty($data['phone'])) {
                if (preg_match($phonePattern, $content[count($content) - 3])) {
                    $data['phone'] = $content[count($content) - 3];
                }
            }
            if (!empty($content[count($content) - 3]) && empty($data['name'])) {
                $j = count($content) - 3;
                if (strpos($content[count($content) - 3], '[') !== false) {
                    $nameArr = explode('[', $content[count($content) - 3]);
                    if (!empty($nameArr[0])) $data['name'] = $nameArr[0];
                } else {
                    if (empty($data['phone']) || empty($data['name'])) {
                        if (preg_match($phonePattern, $content[count($content) - 3])) {
                            $data['phone'] = $content[count($content) - 3];
                        } else {
                            $name = mb_substr($content[count($content) - 3], 0, 3, 'utf-8');
                            $data['name'] = $name;
                        }
                    }
                }
            }
            if (!empty($content[count($content) - 4]) && empty($data['name'])) {
                $j = count($content) - 4;
                if (strpos($content[count($content) - 4], '[') !== false) {
                    $nameArr = explode('[', $content[count($content) - 4]);
                    if (!empty($nameArr[0])) $data['name'] = $nameArr[0];
                } else {
                    $name = mb_substr($content[count($content) - 4], 0, 3, 'utf-8');
                    $data['name'] = $name;
                }
            }
            $goodsInfo = '';
            for ($i = 1; $i < $j; $i++) {
                $goodsInfo .= $content[$i];
            }
            $data['goods_info'] = $goodsInfo;
            CommonService::operateResult($data['user_id'], $data['time'], $data, '留言板内容，提交成功！');
            unset($data['time']);
            $messId = MessBoardModel::query()->insertGetId($data);
            $messInfo = MessBoardModel::query()->where('id', $messId)->first();
            $messInfo['is_oneself'] = 1;
            $adminInfo = AdminModel::query()->select(
                'username',
                'nickname'
            )->where(['id' => $messInfo['user_id']])->first();
            $messInfo['username'] = $adminInfo['username'] ?? '';
            $messInfo['nickname'] = $adminInfo['nickname'] ?? '';
            $messInfo['created_at'] = date('Y/m/d H:i:s', strtotime($messInfo['created_at']));
            $res = self::splitKeywordList($messInfo['goods_info']);
            if (!empty($res['code'])) return $res['msg'];
            $messInfo['keyword_list'] = array_values(array_unique(array_filter($res)));
            $messInfo['express_name'] = '';
            $messInfo['express_no'] = '';
            if (!empty($messInfo['express'])) {
                if (strpos($messInfo['express'], '--') !== false) {
                    $expressArr = explode('--', $messInfo['express']);
                    $messInfo['express_name'] = $expressArr[0] ?? '';
                    $messInfo['express_no'] = $expressArr[1] ?? '';
                }
            }
            return ['code' => 0, 'msg' => 'success', 'data' => $messInfo];
        } catch (\Exception $e) {
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    public static function messBoardContentList($data): array
    {
        if ((int)$data['currentPage'] === 1) {
            $messIdArr = MessBoardModel::query()->where([
                'main_id' => $data['main_id'],
                ['user_id', '!=', $data['user_id']]
            ])->pluck('id')->toArray();
            if (!empty($messIdArr)) {
                foreach ($messIdArr as $mVal) {
                    if (LookMessUserModel::query()
                        ->where([
                            'user_id' => $data['user_id'],
                            'mess_board_id' => $mVal
                        ])->doesntExist()) {
                        LookMessUserModel::query()->insert([
                            'user_id' => $data['user_id'],
                            'mess_board_id' => $mVal,
                            'is_look' => 1
                        ]);
                    }
                }
            }
        }
        $query = MessBoardModel::query()
            ->select('*',
                'id as mess_board_id'
            )->where([
                'main_id' => $data['main_id'],
            ])->where(function ($query) use ($data) {
                if (!empty($data['keyword'])) {
                    $query->where('content', 'like', '%' . $data['keyword'] . '%');
                }
                if (isset($data['userId'])) {
                    $query->where([
                        'user_id' => $data['userId']
                    ]);
                }
            });
        if (!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = $startTimeArr[0] . ' 00:00:00';
        }
        if (!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = $endTimeArr[0] . ' 23:59:59';
        }
        if (!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('created_at', [$startTime, $endTime]);
        } else if (!empty($startTime) && empty($endTime)) {
            $query->where('created_at', '>=', $startTime);
        } else if (empty($startTime) && !empty($endTime)) {
            $query->where('created_at', '<=', $endTime);
        }
        $list = $query->orderBy('id', 'DESC')
            ->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();
        if ($list['data']) {
            foreach ($list['data'] as &$val) {
                $val['is_oneself'] = 0;
                if ($val['user_id'] == $data['user_id']) {
                    $val['is_oneself'] = 1;
                }
                $adminInfo = AdminModel::query()->select(
                    'username',
                    'nickname'
                )->where(['id' => $val['user_id']])->first();
                $val['username'] = $adminInfo['username'] ?? '';
                $val['nickname'] = $adminInfo['nickname'] ?? '';
                $val['created_at'] = date('Y/m/d H:i:s', strtotime($val['created_at']));
                 $res = self::splitKeywordList($val['goods_info']);
                 if (!empty($res['code'])) return $res['msg'];
                 $val['keyword_list'] = array_values(array_unique(array_filter($res)));
                $val['express_name'] = '';
                $val['express_no'] = '';
                if (!empty($val['express'])) {
                    if (strpos($val['express'], '--') !== false) {
                        $expressArr = explode('--', $val['express']);
                        $val['express_name'] = $expressArr[0] ?? '';
                        $val['express_no'] = $expressArr[1] ?? '';
                    }
                }
            }
        }
        return $list;
    }


    public static function selGoodsList($data): array
    {
        $res = [];
        if (!empty($data['req_type'])) {

            $res = MessBoardModel::sellSelGoodsList($data);
        } else {
            $res = MessBoardModel::materielSelGoodsList($data);
        }
        return $res;
    }

    /**
     *创建单据
     * Author: zlf
     * Created at 2024/7/12 11:14
     * @param $data
     * @return array
     */
    public static function addBills($data): array
    {
        $res = [];
        if (!empty($data['req_type'])) {
            unset($data['req_type']);
            $res = self::addSell($data);
        } else {
            unset($data['req_type']);
            $res = self::addMateriel($data);
            if ($res['code'] === 0) {
                $res['data'] = $res['data']['id'];
            }
        }
        return $res;
    }

    /**
     * Author: zlf
     * Created at 2024/7/9 14:54
     * @param $content
     * @param $pattern
     * @return array
     */
    private static function baiDuIdentify($content): array
    {
        $client = new \AipNlp(
            config('app.bd_api_id'),
            config('app.bd_api_key'),
            config('app.bd_secret_key')
        );
        $data = [];
        $address = $client->address($content);
        if (!empty($address)) {
            if (!empty($address['province']) || !empty($address['province']) || !empty($address['county'])) {
                $data['phone'] = strlen($address['phonenum']) == 11 ? $address['phonenum'] : '';
                if (!empty($data['phone']) && !empty($address['person'])) {
                    $data['name'] = $address['person'] ?? '';
                }
                // 假设你要处理的字符串是 $string
                $string = $address['text'];
                $search = '[';
                $result = Str::before($string, $search);
                $data['address'] = $result;
            }
        }
        return $data;
    }

    public static function selUserList($data): array
    {
        $info = AdminModel::query()->select(
            'id as user_id',
            'username',
            'nickname',
        )->where([
            'id' => $data['main_id'],
            'delete_flag' => 0
        ])->first();
        $list = AdminModel::query()
            ->select(
                'id as user_id',
                'username',
                'nickname',
            )->where([
                'parent_id' => $data['main_id'],
                'delete_flag' => 0
            ])->orderBy('id', 'DESC')
            ->get()->toArray();
        if (!empty($list)) {
            $list[count($list)] = $info;
        } else {
            $list[] = $info;
        }
        return $list;
    }

    /**
     *拆分关键词列表
     * Author: zlf
     * Created at 2024/7/10 17:56
     * @param $keyword
     */
    private static function splitKeywordList($keyword): ?array
    {
        $config = new Config();
        $config->accessKeyId = 'LTAI5tDor4tV4pJtPRhsvMRH';
        $config->accessKeySecret = 'cu2XEQlN3GVLKzHB7h8pLo6SflNMgr';
        $config->regionId = "cn-hangzhou";
        $config->endpoint = "alinlp.cn-hangzhou.aliyuncs.com";
        $client = new Alinlp($config);
        $req = new GetNerChEcomRequest();
        $req->serviceCode = 'alinlp';
        $req->text = $keyword;
        $req->LexerId = 'ECOM';
        $wordsArr = [];
        try {
            $response = $client->getNerChEcom($req);
            //$json = json_encode($response->body, JSON_THROW_ON_ERROR);
            if (!empty($response->body->data)) {
                $arr = json_decode($response->body->data, true, 512, JSON_THROW_ON_ERROR);
                if ($arr['success'] === true) {
                    $charArr = [
                        ',', '，', '+', ' ', ' ', '(', '（', ')', '）', '[', ']',
                        '{', '}', '【', '】', '.', '。', '-', '=', '&', '*', '^',
                        '$', '%', '@', '?', '|', '/', '#', ':', '：', ';'
                    ];
                    foreach ($arr['result'] as $rVal) {
                        if (!in_array($rVal['word'], $charArr, true))
                            $wordsArr[] = $rVal['word'];
                    }
                }
            }
            return $wordsArr;
        } catch (TeaUnableRetryError $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }

    private static function addSell($data): array
    {
        $customerInfo = SupplierCustomerModel::query()
            ->where([
                'name' => $data['consignee'],
                'phone' => $data['phone'],
                'main_id' => $data['main_id'],
                'type' => 1
            ])->first();

        if (empty($customerInfo)) {
            $customerId = SupplierCustomerModel::query()
                ->insertGetId([
                    'name' => $data['consignee'],
                    'phone' => $data['phone'],
                    'address' => $data['address'],
                    'main_id' => $data['main_id'],
                    'user_id' => $data['user_id'],
                    'created_at' => $data['time'],
                    'type' => 1
                ]);
        } else {
            $customerId = $customerInfo['id'];
        }
        $data['customer_id'] = $customerId;
        $data['customer_name'] = $data['consignee'];
        $data['is_zero_suppression'] = 0;
        $data['is_draft'] = 0;
        $data['is_auto_out_storage'] = 0;
        $data['sell_date'] = date('Y-m-d H:i:s', $data['time']);
        $mainInfo = $data;
        $mainInfo['created_at'] = $data['time'];
        $mainInfo['sell_date'] = $data['time'];
        $mainInfo['sell_time'] = strtotime(date('Y-m-d', $data['time']));
        $mainInfo['order_no'] = CommonService::getOrderNo(new SellModel, 'order_no', 'S');//订单号
        unset(
            $mainInfo['goods_info'],
            $mainInfo['isUseShelf'],
            $mainInfo['isShareShelfLocation'],
            $mainInfo['time'],
            $mainInfo['batch_title'],
            $mainInfo['sell_logistics_info']
        );
        return SellService::add(
            $mainInfo,
            $data,
            $data['isUseShelf'],
            $data['isShareShelfLocation']
        );
    }

    private static function addMateriel($data): array
    {
        $customerInfo = SupplierCustomerModel::query()
            ->where([
                'name' => $data['consignee'],
                'phone' => $data['phone'],
                'main_id' => $data['main_id'],
                'type' => 0
            ])->first();

        if (empty($customerInfo)) {
            $customerId = SupplierCustomerModel::query()
                ->insertGetId([
                    'name' => $data['consignee'],
                    'phone' => $data['phone'],
                    'address' => $data['address'],
                    'main_id' => $data['main_id'],
                    'user_id' => $data['user_id'],
                    'created_at' => $data['time'],
                    'type' => 0
                ]);
        } else {
            $customerId = $customerInfo['id'];
        }
        $data['supplier_customer_id'] = $customerId;
        $data['deliver_person'] = $data['consignee'];
        $data['deliver_phone'] = $data['phone'];
        $data['deliver_address'] = $data['address'];
        $data['tax_rate'] = 0;
        $data['preferential_way'] = 0;
        $data['preferential_money'] = 0;
        $data['is_auto_out_storage'] = 0;
        $data['purchase_time'] = date('Y-m-d H:i:s', $data['time']);
        $data['purchase_no'] = CommonService::getOrderNo(new MaterielModel, 'purchase_no', 'C');
        $data['materiel_content'] = $data['goods_info'];
        unset(
            $data['consignee'],
            $data['phone'],
            $data['address'],
            $data['time'],
            $data['goods_info']
        );
        return MaterielService::add(
            $data,
            $data['isUseShelf'],
            $data['isShareShelfLocation']
        );
    }

    /**
     *留言新消息
     * Author: zlf
     * Created at 2024/7/15 10:23
     * @param $data
     * @return int
     */
    public static function isNewBoardContent($data): int
    {

        $i = 0;
        $messIdArr = MessBoardModel::query()->where([
            'main_id' => $data['main_id'],
            ['user_id', '!=', $data['user_id']]
        ])->pluck('id')->toArray();
        if (!empty($messIdArr)) {
            foreach ($messIdArr as $mVal) {
                if (LookMessUserModel::query()->where([
                    'user_id' => $data['user_id'],
                    'mess_board_id' => $mVal,
                ])->doesntExist()) {
                    $i++;
                }
            }
        }
        return $i;
    }
}
